﻿var DetailTypeValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var DetailTypeIDView = 0;
var IsDeleteView = false;
var DetailTypeComElem = null;
var DetailTypeComElemVal = null;
var DetailTypeTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupDetailType") != -1) {
        $.validator.addMethod("SetupDetailTypeRequireds", $.validator.methods.required, Messages["SetupDetailTypeRequireds"]);
        $.validator.addMethod("SetupDetailTypeMaxLength30", $.validator.methods.maxlength, Messages["SetupDetailTypeMaxLength30"]);
        $.validator.addClassRules({
            Required: {
                SetupDetailTypeRequireds: true,
            },
            MaxLength30: {
                SetupDetailTypeMaxLength30: 30,
            },
        });

        $('#LoadDetailTypeDetailsForm').validate();
        LoadDetailTypeGrid();
    }
});
$(document).on('change', '.ChangedDetailTypeElements', function () {
    $('#DetailTypeDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.DetailTypeAddElementChange', function () {
    $('#DetailTypeAddBtn').addClass('BackColorRed');
});
function DeleteDetailType(DetailTypeID) {
    jConfirm('Are you sure you want to delete this Detail Type?', 'Warning!', function (retVal) {
        if (retVal == true) {
            DetailTypeIDView = DetailTypeID;
            IsDeleteView = true;
            LoadDetailTypeGrid();
        }
    });
}
function AddNewDetailType() {
    DetailTypeValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewDetailType"],
        type: 'GET',
        success: function (data) {
            $("#AddNewDetailTypeDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewDetailTypePopUp("AddNewDetailTypeDiv");
        }
    });
}
$(document).on('click', '#DetailTypeMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadDetailTypeGrid();
});
$(document).on('click', '#DetailTypeSearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadDetailTypeGrid();
});
function AddNewDetailTypePopUp(PopUpDiv) {
    $.colorbox({
        width: "600px",
        height: "245px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#DetailTypeAddBtn', function () {
    var $form = $('#AddNewDetailTypeForm');
    if ($form.valid()) {
        DetailTypeValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#DetailTypeAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                IsDeleteView = false;
                LoadDetailTypeGrid();
            }
        });
    }
    else
        DetailTypeValidationClientSideHide = true;
});
$(document).on('click', '#DetailTypeDetailsSaveBtn', function () {
    var $form = $('#LoadDetailTypeDetailsForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#DetailTypeDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    IsDeleteView = false;
                    LoadDetailTypeGrid();
                }
            });
        }
        else
            jAlert("You have not data to save:", "Attention!");
    }
});
function LoadDetailTypeGrid() {
    var SetupDetailTypesGridViewModel = {
        SelectedDetailVendorTypeIDText: $("#SelectedDetailVendorTypeIDText").val(),
        DetailTypeDescriptionText: $("#DetailTypeDescriptionText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        DetailTypeID: parseInt(DetailTypeIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupDetailTypesGridViewModel);
    $.ajax({
        url: urls["SetupLoadDetailTypesGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupDetailTypeGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            VendorTypeDrop();
        }
    });
}
function VendorTypeDrop()
{
    $(".VendorTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.VendorTypeDrop', function () {
    $(".VendorTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (DetailTypeTimerId == null) {
        DetailTypeComElem = $(this).attr('id');
        DetailTypeComElemVal = $("#" + DetailTypeComElem).val();
        DetailTypeTimerId = setInterval(function () {

            var keyword = $("#" + DetailTypeComElem).val();
            if (keyword == DetailTypeComElemVal) {
                var PropName = "";
                if (DetailTypeComElem.indexOf("DetailTypeDescriptionText") != -1)
                    PropName = "DetailTypeDescriptionText";

                var position = $("#" + DetailTypeComElem).offset();
                position.top = position.top + $("#" + DetailTypeComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + DetailTypeComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(DetailTypeTimerId);
                        DetailTypeTimerId = null;
                    }
                });
            }
            else
                DetailTypeComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + DetailTypeComElem).val(val);
    if (DetailTypeComElem.indexOf("DetailTypeDescriptionText") != -1)
        $("#" + DetailTypeComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#DetailTypeAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewDetailTypeForm").empty();
                LoadDetailTypeGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewDetailTypeForm").empty();
        LoadDetailTypeGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (DetailTypeValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});